from django.contrib.auth.hashers import make_password, check_password
from django.core.mail import send_mail
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
import re
from .serializers import *
import jwt
import datetime
from django.conf import settings

from .tasks import send_email_task
from itsdangerous import TimedJSONWebSignatureSerializer

token_ser = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 1800)
login_ser = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 86400)


# Create your views here.

class RoleView(APIView):
    # 角色增加
    def post(self, request):
        # {'name': ['普通用户']}
        name = request.data.get('name')
        print(name)
        role_obj = Role.objects.filter(name=name)

        if role_obj:
            return Response({'msg': '角色已存在', 'code': 400})

        # 反序列化添加
        role_ser = RoleModelSerializers(data=request.data)

        if role_ser.is_valid():
            role_ser.save()
            return Response({'msg': 'OK', 'code': 200})

        else:
            return Response({'error': role_ser.errors})


class RegisterView(APIView):
    """
    @author: liqianpeng
    @date: 2020-09-25
    注册：
    {'username': ['xxx'], 'password': ['xxxxx'], 'password2': ['xxxxx'],
    'phone': ['13333333'], 'email': ['11xxx@qq.com'], 'role': ['1']}
    """

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        password1 = request.data.get('password2')
        phone = request.data.get('phone')  # 手机号
        email = request.data.get('email')  # 邮箱
        role_id = request.data.get('role')
        print(username, password, password1, phone, email, role_id)
        if not all([username, password, password1, phone, email, role_id]):  # 查看获取到的数据是否完整
            return Response({'msg': '数据不完整', 'code': 400})

        phone_re = re.compile(r'^1(3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8[0-9]|9[0-9])\d{8}$')  # 正则判断手机号
        if not re.search(phone_re, phone):
            return Response({'msg': '手机号不符合规范', 'code': 400})

        user_obj = User.objects.filter(username=username)

        if user_obj:
            return Response({'msg': '用户已存在', 'code': 400})

        if password1 == password:
            user_data = {'username': username, 'password': make_password(password),
                         'phone': phone, 'email': email, 'role': role_id}  # status有默认值  不写也可以
            user_ser = UserModelSerializers(data=user_data)
            if user_ser.is_valid():
                user_ser.save()
                user_info = {'user_id': user_ser.data.get('id')}
                token = token_ser.dumps(user_info).decode()  # decode()  转码
                send_email_task(username, token, email)

                return Response({'msg': '注册成功', 'code': 200})

        else:
            return Response({'msg': '两次密码不一致', 'code': 400})


class ActiveView(APIView):

    def get(self, request):
        return Response({'msg': 'OK', 'code': 200})


class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        user_obj = User.objects.filter(username=username).first()

        if user_obj:
            if check_password(password, user_obj.password):

                user_info = {'user_id': user_obj.pk}
                token = login_ser.dumps(user_info).decode()
                return Response({'msg': 'OK', 'code': 200, 'username': username, 'role': user_obj.role.name, 'token': token})
            else:
                return Response({'msg': 'ON', 'code': 400})
        else:
            return Response({'msg': 'ON', 'code': 400})
